package com.lee.query;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.val;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.FuzzyQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import java.io.IOException;

/**
 * @Description TODO
 * @Author winston
 * @DateTime 2022/3/10
 */
public class HitQuery {

    private static RestHighLevelClient client;
    @BeforeAll
    public static void init() {
        client = new RestHighLevelClient(RestClient.builder(HttpHost.create("https://elasticsearch-dev.souban.io")));
    }
    @AfterAll
    private static void destory() throws IOException {
        client.close();
    }

    @Test
    public void fuzzyQuery() throws IOException {


        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<em>");
        highlightBuilder.postTags("</em>");
        highlightBuilder.field("name");

        final TermsQueryBuilder termQueryBuilder = QueryBuilders.termsQuery("gender", "男");
        final SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.highlighter(highlightBuilder);
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(10);


        final SearchRequest request = new SearchRequest();
        request.indices("user");
        request.source(searchSourceBuilder);
        final SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
        searchResponse.getHits().forEach(i -> System.out.println(i.getSourceAsString()));
    }
}
